<template>
	<view class="collect-page tn-safe-area-inset-bottom">
		<!-- 顶部导航栏 -->
		<tn-nav-bar fixed :isBack="true" backgroundColor="#FFFFFF" :bottomShadow="false">
			校友组织
		</tn-nav-bar>

		<!-- 搜索栏 -->
		<view class="search-box tn-margin-top">
			<tn-input v-model="searchKeyword" placeholder="搜索校友组织" clearable @input="handleSearch" @clear="handleClear">
				<template #prefix>
					<view class="tn-icon-search tn-padding-right-sm"></view>
				</template>
			</tn-input>
		</view>

		<!-- 加载中提示 -->
		<view v-if="loading" class="loading">
			<tn-loading type="circle" size="36"></tn-loading>
			<text class="loading-text">加载中...</text>
		</view>

		<view class="organization-list" v-else>
			<!-- 搜索结果为空时显示 -->
			<view v-if="filteredOrganizations.length === 0 && (searchKeyword || !loading)" class="empty-result">
				<image src="/static/empty.png" mode="widthFix" class="empty-img"></image>
				<text>未找到 "{{ searchKeyword || '相关' }}" 组织</text>
			</view>

			<!-- 搜索结果列表 -->
			<view class="organization-item" v-for="(item, index) in filteredOrganizations" :key="item.id"
				@click="handleItemClick(item)">
				<image class="organization-avatar" :src="item.avatar || '/static/default-org.png'" mode="aspectFit">
				</image>
				<view class="organization-info">
					<view class="organization-name">
						<!-- 高亮显示匹配的关键词 -->
						<text v-for="(part, i) in highlightKeyword(item.name)" :key="i"
							:class="{ 'highlight': part.highlight }">
							{{ part.text }}
						</text>
					</view>
					<view class="organization-meta">
						<text>活动：{{ item.activityCount || 0 }}</text>
						<text>成员：{{ item.memberCount || 0 }}</text>
					</view>
					
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchKeyword: '',
				organizationList: [], // 原始组织列表（从接口获取）
				loading: true, // 加载状态
				timer: null // 搜索防抖定时器
			}
		},
		onLoad() {
			// 页面加载时获取组织列表
			this.fetchOrganizationList();
		},
		computed: {
			// 过滤后的组织列表
			filteredOrganizations() {
				if (!this.searchKeyword) {
					return this.organizationList;
				}

				const keyword = this.searchKeyword.toLowerCase();
				return this.organizationList.filter(item =>
					item.name?.toLowerCase().includes(keyword)
				);
			}
		},
		methods: {
			// 从接口获取组织列表
			fetchOrganizationList() {
				this.loading = true;
				uni.request({
					url: 'http://localhost:8080/api/organization/list', // 后端接口地址（小程序需配置合法域名）
					method: 'GET',
					success: (res) => {
						this.loading = false;
						if (res.data.code === 200) { // 假设后端成功状态码为200
							this.organizationList = res.data.data || [];
						} else {
							uni.showToast({
								title: '数据获取失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						this.loading = false;
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
						console.error('请求失败：', err);
					}
				});
			},

			// 搜索处理（防抖）
			handleSearch() {
				// 清除之前的定时器
				if (this.timer) clearTimeout(this.timer);
				// 300ms防抖，避免频繁触发
				this.timer = setTimeout(() => {
					this.handleSearchAction();
				}, 300);
			},

			// 搜索实际处理逻辑
			handleSearchAction() {
				if (this.searchKeyword && this.filteredOrganizations.length === 0) {
					uni.showToast({
						title: `未找到"${this.searchKeyword}"相关组织`,
						icon: "none",
						duration: 2000
					});
				}
			},

			// 清除搜索
			handleClear() {
				this.searchKeyword = '';
			},

			// 点击组织项跳转详情
			handleItemClick(item) {
				uni.navigateTo({
					url: `/homePages/organizationDetail?id=${item.id}&name=${encodeURIComponent(item.name || '')}`
				});
			},

			// 高亮显示关键词
			highlightKeyword(name) {
				if (!name || !this.searchKeyword) {
					return [{
						text: name || '',
						highlight: false
					}];
				}

				const keyword = this.searchKeyword;
				const lowerName = name.toLowerCase();
				const lowerKeyword = keyword.toLowerCase();
				const index = lowerName.indexOf(lowerKeyword);

				if (index === -1) {
					return [{
						text: name,
						highlight: false
					}];
				}

				const parts = [];
				if (index > 0) {
					parts.push({
						text: name.substring(0, index),
						highlight: false
					});
				}

				parts.push({
					text: name.substring(index, index + keyword.length),
					highlight: true
				});

				if (index + keyword.length < name.length) {
					parts.push({
						text: name.substring(index + keyword.length),
						highlight: false
					});
				}

				return parts;
			}
		},
		onUnload() {
			// 页面卸载时清除定时器
			if (this.timer) clearTimeout(this.timer);
		}
	};
</script>

<style scoped>
	.collect-page {
		background-color: #f5f7fa;
		min-height: 100vh;
		padding-top: 120rpx;
	}

	.search-box {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;
		position: fixed;
		top: 100rpx;
		left: 0;
		right: 0;
		z-index: 999;
	}

	.search-box .tn-input {
		flex: 1;
	}

	.organization-list {
		padding: 160rpx 30rpx 30rpx;
	}

	.organization-item {
		display: flex;
		align-items: flex-start;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
	}

	/* 小程序点击反馈 */
	.organization-item:active {
		background-color: #f8f9fa;
		transform: scale(0.98);
	}

	.organization-avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
		/* 适配小程序图片加载失败 */
		background-color: #f1f1f1;
	}

	.organization-info {
		flex: 1;
	}

	.organization-name {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
		margin-bottom: 12rpx;
		line-height: 1.4;
	}

	.organization-meta {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 12rpx;
		display: flex;
		justify-content: space-between;
	}

	.organization-meta text {
		margin-right: 20rpx;
	}

	.tn-icon-search {
		color: #999;
		font-size: 32rpx;
	}

	/* 加载中样式 */
	.loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 100rpx 0;
	}

	.loading-text {
		font-size: 28rpx;
		color: #999;
		margin-top: 20rpx;
	}

	/* 空结果样式 */
	.empty-result {
		text-align: center;
		padding: 60rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.empty-img {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
		opacity: 0.5;
	}

	/* 关键词高亮样式 */
	.highlight {
		color: #007aff;
		font-weight: bold;
	}
</style>